package com.ruixi.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Created by lrzg
 * @Date 2022/8/10 11:04
 * @Description http://localhost:8888/druid/datasource.html
 */
//@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    //后台监控:因为springboot内置了servlet容器，使用没有web.xml，可以用ServletRegistrationBean替代
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        //后台需要有人登陆，账号密码
        HashMap<String,String> initParameters = new HashMap<>();
        //增加配置
        initParameters.put("loginUsername","admin");  //登陆参数是固定的
        initParameters.put("loginPassword","123456");
        //允许谁可以访问
        initParameters.put("allow","");//默认就是允许所有访问 ip白名单(没有配置或者为空，则允许所有访问)
        initParameters.put("deny","192.168.10.10");// ip黑名单 (存在共同时，deny优先于allow)
        initParameters.put("resetEnable","true");//允许页面reset
        bean.setInitParameters(initParameters);  //设置初始化参数
        return bean;
    }

    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //过滤那些请求
        Map<String,String> initParams = new HashMap<>();
        //不过滤的
        initParams.put("exclusions","*.js,*.css,*.png,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return  bean;
    }

}
